package com.example.moonshine.redchange.Fragment;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.moonshine.redchange.Activity.BroadCastManager;
import com.example.moonshine.redchange.Activity.MaintwoActivity;
import com.example.moonshine.redchange.Data.ListData;
import com.example.moonshine.redchange.Data.TaskListData;
import com.example.moonshine.redchange.Helper.DataDBHepler;
import com.example.moonshine.redchange.R;
import com.example.moonshine.redchange.Util.DataUrl;
import com.example.moonshine.redchange.Util.SaveParmasUtrl;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;


/**
 * Created by moonshine on 2018/2/4.
 */

public class FirstFragment extends Fragment {
    View view;
    ArrayList postlist = new ArrayList();
    ListView listView;
    PostAdapter postAdapter;
    DataDBHepler dbHepler;
    List<ListData> listData;
    String[] sysIdPotion=new String[]{};
    String[] sysname=new String[]{};
    String sysId=null;
    private LocalReceiver mReceiver;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fg1, container, false);

        SaveParmasUtrl saveParmasUtrl = new SaveParmasUtrl();
        sysId =  saveParmasUtrl.getInfo(getContext(),"sysids","login");
        Log.i(TAG,"sysids:"+sysId);
        sysIdPotion = sysId.split(",");
        Log.i(TAG,"sysIdPotion:"+sysIdPotion);
        sysname = saveParmasUtrl.getInfo(getContext(),"sysname","login").split(",");
        initSpinner();
        //下拉刷新
        final RefreshLayout refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                try {
                    init();
                    refreshlayout.finishRefresh(true/*,false*/);//传入false表示刷新失败
                    Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                    refreshlayout.finishRefresh(false/*,false*/);//传入false表示刷新失败
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(true/*,false*/);//传入false表示加载失败
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
//        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));
//设置 Footer 为 球脉冲 样式
//        refreshLayout.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        return view;
    }

    public void initSpinner() {
        final Spinner sp;
        sp = view.findViewById(R.id.TD_Spinner);
        final String[] list = new String[sysname.length];
        for (int i=0; i<sysname.length;i++)
        {
            String sting = sysname[i];
            list[i]=sting;
            Log.i(TAG, "数据为"+sting);
        }
        //第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
        final ArrayAdapter<String> listadapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_text, list);
        //为适配器设置下拉列表下拉时的菜单样式。
        listadapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
        //将适配器添加到下拉列表上
        sp.setAdapter(listadapter);
        //为下拉列表控框定义点击，这个时间相应，菜单被点中
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView tv = (TextView)view;
                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);
                Log.i(TAG, "位置" + position);
                StringBuffer sb = new StringBuffer();
                sysId = sb.append(sysIdPotion[position]).toString();
                listadapter.notifyDataSetChanged();
                postlist.clear();
                initView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void initView(){

       listView = view.findViewById(R.id.Tasklist);
        postAdapter = new PostAdapter(getContext(), postlist);
        listView.setAdapter(postAdapter);
         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                if (listData.get(position).getStatus().equals("2")) {
//                    设置传送url
                    Log.i("tag","该订单状态："+listData.get(position).getStatus());
                    ListData data = (ListData) postlist.get(position);
                    String oid = data.getOrderId();
                    SaveParmasUtrl saveParmasUtrl = new SaveParmasUtrl();
                    saveParmasUtrl.saveInfo(getContext(),"oid",oid,"login");
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), MaintwoActivity.class);
                    startActivity(intent);
                }else {
                    Toast.makeText(getContext(),"该订单还未生产",Toast.LENGTH_SHORT).show();
                }
            }
        });
     new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    new AnotherTask().execute("");
                }catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),"网络无连接",Toast.LENGTH_SHORT).show();
                }

            }
        }).start();
    }

    public void init(){
        postlist.clear();
        postAdapter.notifyDataSetChanged();
        new Thread(new Runnable() {
            @Override
            public void run() {
                new AnotherTask().execute("");
            }
        }).start();
    }

    @SuppressLint("StaticFieldLeak")
    private class AnotherTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String result) {
            //对UI组件的更新操作
            Gson gson = new Gson();
            try {
                TaskListData postlistData = gson.fromJson(result, TaskListData.class);
                listData = postlistData.getValues();
                Log.i("tag","数据："+listData);
                if (listData.size()==0)
                {
                    Toast.makeText(getContext(),"数据为空",Toast.LENGTH_SHORT).show();
                }else {
                    for(int i = 0;i<listData.size();i++) {
                        String id = listData.get(i).getOrderId();
                        String name = listData.get(i).getcName();
                        String contractNtime = listData.get(i).getContractName();
                        String status = listData.get(i).getStatus();
                        ListData p = new ListData(id, name, contractNtime,status);
                        postlist.add(p);
                    }
                }
            }catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getContext(),"数据为空",Toast.LENGTH_SHORT).show();
            }
            postAdapter.notifyDataSetChanged();
        }
        @Override
        protected String doInBackground(String... params) {
            //耗时的操作
//            String auditedUrl = "http://119.23.219.22:80/element-plc/order/audited";

            if(sysId.equals(""))
            {
                sysId = "sysid";
            }
            Log.i("tag","sysId:"+sysId);
            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            FormBody body = new FormBody.Builder()
                    .add("sysIds",sysId.replace("[","").replace("]",""))
                    .build();
            Request request = new Request.Builder()
                    .url(new DataUrl().firstFragAuditedUrl)
                    .post(body)
                    .build();
            String result ="";
            try {
                Log.i("tag","sysId:"+sysId);
                Response response = client.newCall(request).execute();
                //获取后台传输的额status状态码
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground: ",e );
            }
            return result;

        }
    }

    public class PostAdapter extends BaseAdapter {

        private ArrayList<ListData> List;
        private Context context;

        PostAdapter(Context context, ArrayList<ListData> list) {
            this.context = context;
            this.List = list;
        }

        @Override
        public int getCount() {
            return List.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            if (view == null) {
                view = view.inflate(context, R.layout.activity_set_item, null);
            }
            TextView tv = view.findViewById(R.id.set_item_id);
            TextView tv1 = view.findViewById(R.id.set_item_name);
            TextView tv2 = view.findViewById(R.id.set_item_Contractname);

            ListData data = List.get(position);
            tv.setText(data.getOrderId());
            tv1.setText(data.getcName());
            tv2.setText(data.getContractName());
            view.setBackgroundColor(Color.parseColor("#FF4081"));
            if (data.getStatus().equals("2"))
            {
                view.setBackgroundColor(Color.parseColor("#FF4081"));
            }else {
                view.setBackgroundColor(Color.parseColor("#F5F5DC"));
            }
            return view;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //发送广播给service
        Intent intent = new Intent();
        intent.putExtra("status", "fragment");
        intent.setAction("service");
        BroadCastManager.getInstance().sendBroadCast(getActivity(), intent);

        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("fragment_home");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(getActivity(), mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //接收广播
    class LocalReceiver extends BroadcastReceiver {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            String text = intent.getStringExtra("text");
            try {
                if (text.equals("000")) {  //刷新列表，更新生产订单
                    init();
                    Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
//                    Log.i("Websocket","websocket："+text);
                }else if (text.equals("111")){
                    showNoProject("一涂左侧厚度过小");
                }else if (text.equals("112")){
                    showNoProject("一涂左侧厚度过大");
                }else if (text.equals("122")){
                    showNoProject("一涂右侧厚度过大");
                }else if (text.equals("121")){
                    showNoProject("一涂右侧厚度过小");
                }else if (text.equals("211")){
                    showNoProject("二涂左侧厚度过小");
                }else if (text.equals("212")){
                    showNoProject("二涂左侧厚度过大");
                }else if (text.equals("222")){
                    showNoProject("二涂右侧厚度过大");
                }else if (text.equals("221")){
                    showNoProject("二涂右侧厚度过小");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//            Log.i("tag", "frag传参的数字为:" + text);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BroadCastManager.getInstance().unregisterReceiver(getActivity(),mReceiver);
    }


    //提示警告
    @SuppressLint("ResourceAsColor")
    public void showNoProject(String msg){
        TextView title = new TextView(getContext());
        title.setText("警告");
        title.setGravity(Gravity.CENTER);
        title.setTextSize(20);
        android.support.v7.app.AlertDialog builder = new android.support.v7.app.AlertDialog.Builder(getContext())
                .setMessage(msg)
                .setCustomTitle(title)
                .create();
        builder.show();
    }

}